package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.server.manger.ChannelHotUpdateConfigMgr;
import com.yanqu.road.server.manger.SqlCacheMgr;
import com.yanqu.road.server.manger.WhiteIpMgr;
import com.yanqu.road.web.mgr.ActivityMallMgr;
import com.yanqu.road.web.util.IpAddressHelper;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/adminOperate")
public class
ManagerOperate extends HttpServlet {

	private static Logger logger = LogManager.getLogger(ManagerOperate.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		JSONObject resultObj = new JSONObject();
		resultObj.put("status", 0);
		resultObj.put("msg", "DoPost Fail!");
		String resultStr = resultObj.toJSONString();
		try {
			//校验访问IP
			String ip = IpAddressHelper.getIpAddr(request);
			if(!WhiteIpMgr.isConsoleWhiteIp(ip)){
				resultObj.put("status", -10);        //访问IP非法
				resultObj.put("msg", "访问IP非法");
				resultStr = resultObj.toJSONString();
			}else {
				String param = request.getParameter("param");
				JSONObject jsonObject = JSONObject.parseObject(param);
				String op = jsonObject.getString("op");
				String opParam = jsonObject.getString("param");
				logger.info("op=={}", op);
				logger.info("param=={}", opParam);
				resultStr = GameWebServiceInvoke.executeAdminOperate(op, opParam);
				if("AgentReload|reloadMgr".equals(op) && "{\"content\":\"ActivityMgr\"}".equals(opParam)){
					ActivityMallMgr.reloadActivityData();
				} else if ("AgentReload|reloadMgr".equals(op) && "{\"content\":\"SqlCacheMgr\"}".equals(opParam)) {
					SqlCacheMgr.publicReloadData();
				} else if ("AgentReload|reloadMgr".equals(op) && "{\"content\":\"ChannelHotUpdateConfigMgr\"}".equals(opParam)) {
					new ChannelHotUpdateConfigMgr().reload();
				}

			}
		} catch (Exception ex) {
			logger.error("GMInterface", ex);
			ex.printStackTrace();
		} finally {
			sendMessage(response, resultStr);
		}
	}

	public void sendMessage(HttpServletResponse response, String msg) {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Access-Control-Allow-Origin", "*");
		try {
			response.getWriter().write(msg);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			logger.error("", e);
		}
	}
}
